﻿<template>
  <div class="return-order-audit-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>采购退货单审核管理</h2>
    </div>

    <!-- 搜索栏 -->
    <div class="search-panel">
      <div class="search-form">
        <div class="form-group">
          <label>退货单号</label>
          <input 
            v-model="query.returnNo" 
            @keyup.enter="search" 
            placeholder="请输入退货单号" 
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label>状态</label>
          <select v-model="query.status" class="form-select">
            <option value="">全部</option>
            <option value="1">待审核</option>
            <option value="2">已通过</option>
            <option value="3">已拒绝</option>
          </select>
        </div>
        <button @click="search" class="btn-primary">搜索</button>
        <button @click="reset" class="btn-secondary">重置</button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-panel">
      <div class="panel-header">
        <h3>待审核退货单列表</h3>
        <p>管理所有待审核的退货单</p>
      </div>
      
      <div v-if="loading" class="loading">
        加载中...
      </div>
      
      <div v-else-if="list.length === 0" class="empty">
        暂无数据
      </div>
      
      <div v-else class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>退货单号</th>
              <th>原采购单号</th>
              <th>退货金额</th>
              <th>状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in list" :key="item.id">
              <td>{{ item.returnNo || '-' }}</td>
              <td>{{ item.orderNo || '-' }}</td>
              <td>{{ item.totalReturnAmount || '0.00' }}</td>
              <td>
                <span :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</span>
              </td>
              <td>{{ formatDate(item.createTime) }}</td>
              <td class="action-cell">
                <button @click="viewDetail(item)" class="btn-view">详情</button>
                <button @click="approve(item)" :disabled="item.status !== 1" class="btn-approve">通过</button>
                <button @click="reject(item)" :disabled="item.status !== 1" class="btn-reject">驳回</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button @click="prevPage" :disabled="pageNum === 1" class="btn-page">上一页</button>
      <span class="page-info">
        第 {{ pageNum }} 页，共 {{ Math.ceil(total / pageSize) }} 页，总计 {{ total }} 条
      </span>
      <button @click="nextPage" :disabled="pageNum * pageSize >= total" class="btn-page">下一页</button>
    </div>

    <!-- 详情对话框 -->
    <div v-if="showDetail" class="modal-overlay" @click="closeDetail">
      <div class="modal-content detail-modal" @click.stop>
        <div class="modal-header">
          <h3>退货单详情</h3>
          <button @click="closeDetail" class="btn-close"></button>
        </div>
        
        <div class="modal-body">
          <div v-if="detail" class="detail-content">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-grid">
                <div class="detail-item">
                  <label>退货单号：</label>
                  <span>{{ detail.returnNo || '-' }}</span>
                </div>
                <div class="detail-item">
                  <label>原采购单号：</label>
                  <span>{{ detail.orderNo || '-' }}</span>
                </div>
                <div class="detail-item">
                  <label>供应商：</label>
                  <span>{{ detail.supplierName || '-' }}</span>
                </div>
                <div class="detail-item">
                  <label>退货原因：</label>
                  <span>{{ detail.returnReason || '-' }}</span>
                </div>
                <div class="detail-item">
                  <label>总退货金额：</label>
                  <span>{{ detail.totalReturnAmount?.toFixed(2) || '0.00' }}</span>
                </div>
                <div class="detail-item">
                  <label>状态：</label>
                  <span :class="getStatusClass(detail.status)">{{ getStatusText(detail.status) }}</span>
                </div>
                <div class="detail-item">
                  <label>创建时间：</label>
                  <span>{{ formatDate(detail.createTime) }}</span>
                </div>
                <div class="detail-item">
                  <label>备注：</label>
                  <span>{{ detail.remark || '-' }}</span>
                </div>
              </div>
            </div>
            
            <div class="detail-section">
              <h4>退货商品</h4>
              <div v-if="detail.items && detail.items.length > 0" class="items-table">
                <table>
                  <thead>
                    <tr>
                      <th>商品名称</th>
                      <th>规格型号</th>
                      <th>单位</th>
                      <th>退货数量</th>
                      <th>退货单价</th>
                      <th>退货金额</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(item, index) in detail.items" :key="index">
                      <td>{{ item.productName }}</td>
                      <td>{{ item.specification }}</td>
                      <td>{{ item.unit }}</td>
                      <td>{{ item.returnQuantity }}</td>
                      <td>{{ item.returnUnitPrice?.toFixed(2) || '0.00' }}</td>
                      <td>{{ item.returnAmount?.toFixed(2) || '0.00' }}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
              <div v-else class="empty-items">暂无退货商品</div>
            </div>
          </div>
        </div>
        
        <div class="modal-footer">
          <button @click="closeDetail" class="btn-primary">关闭</button>
        </div>
      </div>
    </div>

    <!-- 审核对话框 -->
    <div v-if="showAudit" class="modal-overlay" @click="closeAudit">
      <div class="modal-content audit-modal" @click.stop>
        <div class="modal-header">
          <h3>{{ auditType === 'approve' ? '审核通过' : '审核驳回' }}</h3>
          <button @click="closeAudit" class="btn-close"></button>
        </div>
        
        <div class="modal-body">
          <div class="form-group">
            <label>审核意见</label>
            <textarea 
              v-model="auditForm.auditOpinion" 
              placeholder="请输入审核意见" 
              class="form-textarea"
              rows="4"
            ></textarea>
          </div>
        </div>
        
        <div class="modal-footer">
          <button @click="closeAudit" class="btn-secondary">取消</button>
          <button @click="submitAudit" class="btn-primary">确认</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { apiGet, apiPost } from '../../utils/api.js'

// 响应式数据
const loading = ref(false)
const list = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)

// 对话框状态
const showDetail = ref(false)
const showAudit = ref(false)
const detail = ref(null)
const auditType = ref('')
const currentItem = ref(null)

// 搜索条件
const query = reactive({
  returnNo: '',
  status: ''
})

// 审核表单
const auditForm = reactive({
  auditOpinion: ''
})

// 生命周期
onMounted(() => {
  load()
})

// 方法
async function load() {
  loading.value = true
  try {
    const params = {
      current: pageNum.value,
      size: pageSize.value,
      ...query
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const qs = new URLSearchParams(params).toString()
    const response = await apiGet(`/procure-service/purchase-return-order/page${qs ? `?${qs}` : ''}`)
    
    console.log('退货审核API响应数据:', response)
    
    // 处理不同的响应结构
    let records = []
    let totalCount = 0

    if (response.data) {
      // 如果响应有data字段
      records = response.data.records || response.data.list || []
      totalCount = response.data.total || 0
    } else if (response.records) {
      // 如果响应直接有records字段
      records = response.records || []
      totalCount = response.total || 0
    } else if (Array.isArray(response)) {
      // 如果响应直接是数组
      records = response
      totalCount = response.length
    }

    console.log('解析后的records:', records)
    console.log('解析后的total:', totalCount)

    list.value = records.map(r => ({ ...r, id: r.id != null ? String(r.id) : r.id }))
    total.value = totalCount

    console.log('处理后的数据:', list.value)
  } catch (error) {
    console.error('加载失败:', error)
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

function search() {
  pageNum.value = 1
  load()
}

function reset() {
  query.returnNo = ''
  query.status = ''
  pageNum.value = 1
  load()
}

function prevPage() {
  if (pageNum.value > 1) {
    pageNum.value--
    load()
  }
}

function nextPage() {
  if (pageNum.value * pageSize.value < total.value) {
    pageNum.value++
    load()
  }
}

async function viewDetail(item) {
  try {
    const response = await apiGet(`/procure-service/purchase-return-order/${item.id}`)
    console.log('退货单详情API响应:', response)
    
    if (response.data) {
      detail.value = response.data
    } else {
      detail.value = response
    }
    showDetail.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    alert('获取详情失败')
  }
}

function closeDetail() {
  showDetail.value = false
  detail.value = null
}

function approve(item) {
  if (item.status !== 1) {
    alert('只有待审核状态的退货单可以审核')
    return
  }
  
  currentItem.value = item
  auditType.value = 'approve'
  auditForm.auditOpinion = ''
  showAudit.value = true
}

function reject(item) {
  if (item.status !== 1) {
    alert('只有待审核状态的退货单可以审核')
    return
  }
  
  currentItem.value = item
  auditType.value = 'reject'
  auditForm.auditOpinion = ''
  showAudit.value = true
}

function closeAudit() {
  showAudit.value = false
  auditType.value = ''
  currentItem.value = null
  auditForm.auditOpinion = ''
}

async function submitAudit() {
  if (!auditForm.auditOpinion.trim()) {
    alert('请输入审核意见')
    return
  }
  
  try {
    const data = {
      returnOrderId: currentItem.value.id,
      auditResult: auditType.value === 'approve' ? 1 : 0,
      auditOpinion: auditForm.auditOpinion
    }
    
    await apiPost('/procure-service/purchase-return-order/audit', data)
    
    alert(auditType.value === 'approve' ? '审核通过成功' : '审核驳回成功')
    closeAudit()
    load()
  } catch (error) {
    console.error('审核失败:', error)
    alert('审核失败')
  }
}

function getStatusText(status) {
  const statusMap = {
    0: '草稿',
    1: '待审核',
    2: '已通过',
    3: '已拒绝'
  }
  return statusMap[status] || '未知'
}

function getStatusClass(status) {
  const classMap = {
    0: 'status-draft',
    1: 'status-pending',
    2: 'status-approved',
    3: 'status-rejected'
  }
  return classMap[status] || ''
}

function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.return-order-audit-management {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.search-panel {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  gap: 20px;
  align-items: end;
  flex-wrap: wrap;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.form-input, .form-select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  width: 200px;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.btn-primary {
  padding: 8px 16px;
  border: 1px solid #3b82f6;
  border-radius: 6px;
  background: #3b82f6;
  color: #fff;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-primary:hover {
  background: #2563eb;
}

.btn-secondary {
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  background: #fff;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-secondary:hover {
  background: #f8f9fa;
}

.data-panel {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.panel-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.panel-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.panel-header p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.loading, .empty {
  padding: 40px;
  text-align: center;
  color: #666;
  font-size: 16px;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
  color: #666;
  background: #f8f9fa;
  font-weight: 600;
  white-space: nowrap;
}

.data-table td {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
}

.action-cell {
  white-space: nowrap;
}

.btn-view, .btn-approve, .btn-reject {
  padding: 4px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
  cursor: pointer;
  margin-right: 8px;
  font-size: 12px;
  transition: all 0.3s;
}

.btn-view {
  color: #909399;
  border-color: #909399;
}

.btn-view:hover {
  background: #909399;
  color: #fff;
}

.btn-approve {
  color: #67c23a;
  border-color: #67c23a;
}

.btn-approve:hover {
  background: #67c23a;
  color: #fff;
}

.btn-reject {
  color: #f56c6c;
  border-color: #f56c6c;
}

.btn-reject:hover {
  background: #f56c6c;
  color: #fff;
}

.btn-view:disabled, .btn-approve:disabled, .btn-reject:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.status-draft {
  color: #909399;
  background: #f4f4f5;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-pending {
  color: #e6a23c;
  background: #fdf6ec;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-approved {
  color: #67c23a;
  background: #f0f9ff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-rejected {
  color: #f56c6c;
  background: #fef0f0;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.btn-page {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  background: #fff;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-page:hover:not(:disabled) {
  background: #f8f9fa;
}

.btn-page:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #666;
  font-size: 14px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  max-width: 800px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.detail-modal {
  max-width: 1000px;
}

.audit-modal {
  max-width: 500px;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-close:hover {
  color: #666;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.detail-content {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 30px;
}

.detail-section h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #3b82f6;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: 500;
  color: #666;
  margin-right: 8px;
  min-width: 100px;
}

.detail-item span {
  color: #333;
}

.items-table table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

.items-table th,
.items-table td {
  padding: 8px;
  border: 1px solid #ebeef5;
  text-align: left;
}

.items-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #666;
}

.empty-items {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.form-textarea {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  width: 100%;
  min-height: 80px;
  resize: vertical;
}

.form-textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}
</style>
